package com.thinkgem.jeesite.common.filter;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.RSAUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.LicenseKey;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权拦截器
 *
 * @author zhangc
 * @version 2013-8-5
 */
public class LicenseFilter implements Filter{
    private static Boolean LICENSEKEYRESULT = false;
    private FilterConfig filterConfig;

    public LicenseFilter(){
    }

    public void init(FilterConfig filterConfig){
        this.filterConfig = filterConfig;
    }

    public void destroy(){
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain chain) throws IOException, ServletException{
        HttpServletRequest request = (HttpServletRequest)rq;
        HttpServletResponse response = (HttpServletResponse)rs;

        LICENSEKEYRESULT = (Boolean)CacheUtils.get("LICENSEKEYRESULT");
        if(null == LICENSEKEYRESULT || !LICENSEKEYRESULT){
            LicenseKey licenseKey = Global.getLicense();
            if(null == licenseKey || StringUtils.isEmpty(Global.getLicense().getLicenseKey())){
                request.setAttribute("license", "error");
            }
            else{
                LICENSEKEYRESULT = Result.SUCCESS.equals(RSAUtils.validateLicense(Global.getLicense().getLicenseKey()).getCode());
                if(LICENSEKEYRESULT){
                    CacheUtils.put("LICENSEKEYRESULT", true);
                }
                else{
                    request.setAttribute("license", "error");
                }
            }
        }

        chain.doFilter(request, response);
    }
}
